﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;

using mvcForum.Core;
using mvcForum.Core.Abstractions.Interfaces;

using mvcForum.Web.Controllers;
using mvcForum.Web.ViewModels;
using mvcForum.Web.ViewModels.Create;

using GroupVM = mvcForum.Web.Areas.ForumAdmin.ViewModels.Group;
using mvcForum.Web.Areas.ForumAdmin.Helpers;
using mvcForum.Web.Interfaces;
using mvcForum.Core.Interfaces.Data;

namespace mvcForum.Web.Areas.ForumAdmin.Controllers {

	public class GroupController : ForumAdminBaseController {
		private readonly IRepository<Group> groupRepo;

		public GroupController(IWebUserProvider userProvider, IContext context)
			: base(userProvider, context) {

			this.groupRepo = this.GetRepository<Group>();
		}

		#region Create
		public ActionResult Create() {
			return View(new CreateGroupViewModel());
		}

		[HttpPost]
		public ActionResult Create(CreateGroupViewModel model) {
			if (ModelState.IsValid) {
				Group group = new Group(model.Name);
				this.groupRepo.Create(group);
				this.Context.SaveChanges();

				return RedirectToAction("Index");
			}
			return View(model);
		}
		#endregion

		#region Read/Update
		public ActionResult Index() {
			// TODO: Access!?!? Only show boards the user has access to!!!
			IEnumerable<Group> groups = this.groupRepo.ReadAll();
			List<GroupViewModel> groupVMs = new List<GroupViewModel>();
			foreach (var group in groups) {
				groupVMs.Add(new GroupViewModel(group));
			}

			return View(groupVMs);
		}

		public ActionResult Update(Int32 id) {
			// TODO: Access!!??!?
			Group group = this.groupRepo.Read(id);
			return View(new GroupVM { Id = group.Id, Path = BreadcrumbHelper.BuildPath(group, Url) });
		}

		[HttpPost]
		public ActionResult Edit(GroupViewModel model) {
			// TODO: Access!!??!?
			if (ModelState.IsValid) {
				var group = this.groupRepo.Read(model.Id);
				group.Name = model.Name;
				this.Context.SaveChanges();

				return RedirectToAction("Index");
			}
			return View(model);
		}
		#endregion

		#region Delete
		public ActionResult Delete(Int32 id) {
			// TODO: Access!!
			var model = new GroupViewModel(this.groupRepo.Read(id));
			return View(model);
		}

		[HttpPost]
		public ActionResult Delete(Int32 id, Boolean confirm) {
			// TODO: Access!!
			var group = this.groupRepo.Read(id);
			if (ModelState.IsValid && confirm) {
				this.groupRepo.Delete(group);
				this.Context.SaveChanges();

				if (Request.IsAjaxRequest()) {
					return Json(true);
				}

				return RedirectToAction("Index");
			}

			if (Request.IsAjaxRequest()) {
				return Json(false);
			}

			var model = new GroupViewModel(group);
			return View(model);
		}
		#endregion
	}
}